package com.example.stock.ui.query;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.example.stock.R;
import com.example.stock.base.BaseFragment;
import com.example.stock.base.CommonCallback;
import com.example.stock.base.Result;
import com.example.stock.config.Config;
import com.example.stock.databinding.FragmentFormBinding;
import com.example.stock.model.GoodsData;
import com.example.stock.util.DBUtil;
import com.example.stock.util.DialogUtils;
import com.example.stock.util.Utils;
import com.example.stock.view.FormLayoutManger;

import java.util.List;
import java.util.Objects;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;

public class FormFragment extends BaseFragment<FragmentFormBinding, QueryViewModel> {

    private FormAdapter adapter;
    private int indexType;
    int allPageCount;
    int curPager;

    public static FormFragment getInstance(int index) {
        FormFragment fragment = new FormFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected Class<QueryViewModel> initViewModel() {
        return QueryViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_form;
    }

    AlertDialog mAlertDialog;

    @Override
    protected void initView() {
        assert getArguments() != null;
        indexType = getArguments().getInt("INDEX", 0);
        mBinding.recyclerTitleView.setLayoutManager(new FormLayoutManger(getContext()));
        FormTitleAdapter adapterTitle = new FormTitleAdapter(indexType);
        mBinding.recyclerTitleView.setAdapter(adapterTitle);
        FormLayoutManger formLayoutManger = new FormLayoutManger(getContext(), mBinding.recyclerView, mBinding.recyclerTitleView);
        mBinding.recyclerView.setLayoutManager(formLayoutManger);
        adapter = new FormAdapter(indexType);
        mBinding.recyclerView.setAdapter(adapter);
        if(indexType == 0){
            adapter.setListener(new CommonCallback<Object>() {
                @Override
                public void onResult(Object... data) {
                    if(mAlertDialog != null && mAlertDialog.isShowing()){
                        return;
                    }
                    GoodsData goodsData = (GoodsData) data[0];
                    int position = (int) data[1];
                    View editView = View.inflate(getContext(), R.layout.dialog_edit, null);
                    AppCompatEditText editText = editView.findViewById(R.id.edit_text);
                    AppCompatTextView tvOk = editView.findViewById(R.id.tv_ok);
                    AppCompatTextView tvCancel = editView.findViewById(R.id.tv_cancel);
                    tvOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String s = editText.getText().toString();
                            if (TextUtils.isEmpty(s)) {
                                return;
                            }
                            goodsData.setSl(s);
                            DBUtil.getInstance().update(goodsData);
                            adapter.getData().set(position, goodsData);
                            adapter.notifyItemChanged(position);
                            mAlertDialog.dismiss();
                        }
                    });
                    tvCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mAlertDialog.dismiss();
                        }
                    });
                    mAlertDialog = new AlertDialog.Builder(getContext())
                            .setView(editView)
                            .create();
                    mAlertDialog.show();
                }
            });
        }
        mBinding.recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void lazyInit() {
        mViewModel.loadAllByType(((QueryActivity) Objects.requireNonNull(getActivity())).getOrderBean(), indexType);
    }

    private void loadData() {
        mViewModel.listByDB(((QueryActivity) Objects.requireNonNull(getActivity())).getOrderBean(), indexType, curPager);
    }

    @Override
    protected void registerObserve() {
        super.registerObserve();
        mViewModel.mBeans.observe(this, new Observer<Result<List<GoodsData>>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onChanged(Result<List<GoodsData>> listResult) {
                adapter.mData.clear();
                adapter.notifyDataSetChanged();
                if (listResult.isSuccess()) {
                    List<GoodsData> data = listResult.getData();
                    if (data != null && data.size() > 0) {
                        adapter.setData(data);
                    } else {
                        if (curPager == 0) {
                            DialogUtils.showInfoDialog(getContext(), "暂无已盘点数据", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    DialogUtils.closeInfoDialog();
                                }
                            });
                        }
                    }
                } else {
                    Utils.getInstance().showToast(listResult.getMsg());
                }
            }
        });
        mViewModel.mCount.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer > -1) {
                    allPageCount = getAllPageCount(integer, Config.PAGE_SIZE);
                    mBinding.tvPage.setText(String.format("%s / %s", curPager + 1, allPageCount));
                    loadData();
                } else {
                    mBinding.tvPage.setText(String.format("%s / %s", 0, 0));
                }
            }
        });
        mBinding.tvNext0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPrePage(v);
            }
        });
        mBinding.tvNext1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNextPage(v);
            }
        });
    }

    /**
     * 获取总页数
     */
    private int getAllPageCount(int allCount, int pageSize) {
        return (allCount - 1) / pageSize + 1;
    }

    public void onPrePage(View view) {
        if (curPager > 0) {
            curPager--;
            loadData();
        } else {
            Utils.getInstance().showToast("当前为最小页码");
        }
    }

    public void onNextPage(View view) {
        if (curPager < allPageCount - 1) {
            curPager++;
            loadData();
        } else {
            Utils.getInstance().showToast("当前为最大页码");
        }
    }
}
